package service

import (
	"errors"
	"github.com/go-admin-team/go-admin-core/sdk/service"
	"tuowei.com/app/admin/models"
	"tuowei.com/app/admin/service/dto"
	"tuowei.com/common/actions"
	cDto "tuowei.com/common/dto"
)

type SysAcademy struct {
	service.Service
}

// GetPage 获取SysCourse列表
func (e *SysAcademy) GetPage(c *dto.SysAcademyGetPageReq, p *actions.DataPermission, list *[]models.SysAcademy, count *int64) error {
	var err error
	var data models.SysAcademy

	err = e.Orm.Debug().
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
			actions.Permission(data.TableName(), p),
		).Table(data.TableName()).Order("academy_hot,academy_id desc").
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return err
	}
	return nil
}

// Insert 创建SysConsultLBT对象
func (e *SysAcademy) Insert(c *dto.SysAcademyInsertReq) error {
	var err error
	var data models.SysAcademy

	c.Generate(&data)

	err = e.Orm.Create(&data).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return err
	}

	return nil
}

func (e *SysAcademy) Update(c *dto.SysAcademyUpdateReq) error {
	var err error
	var model = models.SysAcademy{}
	e.Orm.First(&model, c.GetId())
	c.Generate(&model)
	db := e.Orm.Save(&model)
	err = db.Error
	if err != nil {
		e.Log.Errorf("Service Update SysConsultLBT error:%s", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权更新该数据")

	}
	return nil
}

// Remove 删除SysConsultLBT
func (e *SysAcademy) Remove(d *dto.SysAcademyDeleteReq) error {
	var err error
	var data models.SysAcademy

	db := e.Orm.Model(&data).Delete(&data, d.GetId())
	if db.Error != nil {
		err = db.Error
		e.Log.Errorf("Delete error: %s", err)
		return err
	}
	if db.RowsAffected == 0 {
		err = errors.New("无权删除该数据")
		return err
	}
	return nil
}
